<template>
  <el-row>
    <el-col :span="24">
      <el-form class="el-form-col" :model="model" label-position="left" ref="elForm" label-width="110px">
        <Portlet title="商家信息">
          <el-row :gutter="15" class="row">

            <el-col :lg="8" :md="12" :xl="6">
              <el-form-item label="商家名称:" prop="name" :rules="[
                    {required: true, message: '商家名称必须', trigger: 'blur'}
                  ]">
                <el-input v-model="model.name"></el-input>
              </el-form-item>
            </el-col>

            <el-col :lg="8" :md="12" :xl="6">
              <el-form-item label="所属公司名称:">
                <span>{{ companyName }}</span>
              </el-form-item>
            </el-col>

            <el-col :lg="8" :md="12" :xl="6">
              <el-form-item label="商家联系人:" prop="prin" :rules="[
                  ]">
                <el-input v-model="model.prin"></el-input>
              </el-form-item>
            </el-col>

            <el-col :lg="8" :md="12" :xl="6">
              <el-form-item label="商家联系电话:" label-width="120px" prop="phone" :rules="[
                    {validator: isPhone, message: '电话格式不正确', trigger: 'blur'},
                  ]">
                <el-input v-model="model.phone"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </Portlet>

        <Portlet title="分配账号">
          <el-row :gutter="15">
            <el-col :lg="8" :md="12" :xl="6">
              <el-form-item label="账号姓名:">
                <el-select
                  v-model="model.storageUserId"
                  filterable
                  clearable
                  placeholder="请输入关键词"
                  remote
                  :remote-method="remoteQuery2"
                  :loading="userLoading">
                  <el-option
                    v-for="item in userArr"
                    :key="item.value"
                    :label="item.text"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :lg="8" :md="12" :xl="6">
              <el-form-item label-width="120px" label="绑定登录手机号:">
                <el-input :disabled="true" :value="userPhone"></el-input>
              </el-form-item>
            </el-col>

            <el-col :lg="8" :md="12" :xl="6">
              <el-form-item label-width="120px" label="角色:">
                <el-input :disabled="true" :value="getPosition"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </Portlet>

        <Productions v-if="id" :id="id" canEdit></Productions>

        <Portlet>
          <el-row>
            <el-col :span="24" class="text-center">
              <el-button :loading="loading" @click.prevent="submit" type="primary">
                {{ id ? '保存' : '新增'}}
              </el-button>
            </el-col>
          </el-row>
        </Portlet>
      </el-form>
    </el-col>
  </el-row>
</template>
<script>

import {copy, dotData, alert, confirm} from '@/utils'
import {httpSuccessPost, httpGetResponse} from '@/utils/ajax'
import {filterDataBaseDictionary} from '@/filters'
import {isFormatNumber, isPhone} from '@/utils/validate'
import Productions from '@/views/oms/basicData/owner/Productions'
import L from 'lodash'

export default {
  components: {
    Productions
  },
  filters: {
    filterDataBaseDictionary
  },
  data() {
    return {
      id: this.$route.params.id,
      routeName: this.$route.name,
      loading: false,
      cargoOwnerLoading: false,
      userLoading: false,
      productionSelectModalVisible: false, // 产品选择弹窗默认关闭
      model: {
        name: '',
        compayId: '',
        prin: '',
        phone: '',
        storageUserId: '' // 新增 账号id
      },
      userIdMap: new Map(), // 新建storageUserId map
      userArr: [], // 模糊搜索到的 账号数组
      cargoOwnerArr: [],
      companyName: ''
    }
  },
  computed: {
    // 获取storageUserIdMap对象里面的phone
    userPhone() {
      let temp = this.userIdMap.get(this.model.storageUserId)
      if (temp) {
        return dotData(temp, 'phone')
      }
      return ''
    },
    // 获取Map对象里面的 职位--渲染页面用
    getPosition() {
      let temp = this.userIdMap.get(this.model.storageUserId)
      if (temp) {
        return dotData(temp, 'position')
      }
      return ''
    }
  },
  created() {
    if (this.id) {
      httpGetResponse('/ms-warehouse-order/basicData/findCargoOwnerInfo', {id: this.id}).then(response => {
        const success = dotData(response, 'success')
        if (success) {
          this.model.name = dotData(response, 'data.name')
          this.model.compayId = dotData(response, 'data.compayId')
          this.companyName = dotData(response, 'data.compayName')
          this.model.prin = dotData(response, 'data.prin')
          this.model.phone = dotData(response, 'data.phone')
          this.model.storageUserId = dotData(response, 'data.storageUserId')
          // 根据详情数据 回填 账号信息
          if (this.model.storageUserId) {
            this.userArr = [
              {
                value: this.model.storageUserId,
                text: dotData(response, 'data.userName')
              }
            ]
            // 回填map
            this.userIdMap.set(this.model.storageUserId, {
              phone: dotData(response, 'data.userPhone'),
              position: dotData(response, 'data.roleName')
            })
          }
        }
      })
    } else {
      // 公司信息
      httpGetResponse('/ms-warehouse-order/basicData/findMyCompanyInfo').then(response => {
        console.log(response, 'response')
        const success = dotData(response, 'success')
        if (success) {
          const data = dotData(response, 'data')
          this.model.compayId = data.id
          this.companyName = data.name
        }
      })
    }
  },
  watch: {
    // 监听手动重新选择了账号姓名，useId对象 里面有职位就回填，没有就清空
    // 'model.userId' (val, oldVal) {
    //   let temp = this.userIdMap.get(this.model.id)
    //   let positionVal = dotData(temp, 'position')
    //   if (positionVal) { // 若 手动重新选择userId，且里面有岗位，则回填到modal,反之，清空position
    //     this.model.position = positionVal
    //   } else {
    //     this.model.position = ''
    //   }
    // }
  },
  methods: {
    isFormatNumber,
    isPhone,
    httpPost(url) {
      let data = copy(this.model, true)
      if (this.id) {
        data.id = this.id
      }
      return httpSuccessPost(url, data).then(response => {
        return response
      })
    },
    submit() {
      this.$refs.elForm.validate(result => {
        if (!result) {
          alert('验证未通过')
          return
        }
        this.loading = true
        let title = this.id ? '编辑成功' : '是否需要添加厂家产品?'
        let url = '/ms-warehouse-order/basicData/saveOrUpdateCargoOwner'
        this.httpPost(url).then(response => {
          const success = dotData(response, 'success')
          const id = dotData(response, 'data.id')
          if (success) {
            confirm(title, title, {
              type: 'success',
              showCancelButton: !this.id,
              closeOnClickModal: false
            }).then(_ => {
              if (this.id) {
                this.$router.push({path: '/ss-oms/basic-data/owner/index'})
              } else {
                this.$router.push({path: '/ss-oms/basic-data/owner/edit/' + id})
              }
            }).catch(_ => {
              this.$router.push({path: '/ss-oms/basic-data/owner/index'})
            }).finally(_ => {
              this.resetFields()
              this.loading = false
            })
          } else {
            this.loading = false
          }
        }).catch(_ => {
          this.loading = false
        })
      })
    },
    // 清空表格
    resetFields() {
      try {
        this.$refs.elForm.resetFields()
      } catch (err) {
        console.log(err)
      }
    },
    // 模糊搜索 公司名
    remoteQuery(query) {
      this.cargoOwnerLoading = true
      this.remoteMethod(query, this)
    },
    remoteMethod: L.debounce((query, _this) => {
      if (!query) {
        _this.cargoOwnerLoading = false
        return
      }
      httpGetResponse('/ms-warehouse-order/basicData/findCompanyList', {name: query}).then(response => {
        const success = dotData(response, 'success')
        if (success) {
          let data = dotData(response, 'data')
          let tempArr = []
          if (Array.isArray(data)) {
            data.forEach((v, k) => {
              tempArr.push({
                text: v.name,
                value: v.id
              })
            })
          }
          _this.cargoOwnerArr = tempArr
        }
      }).finally(_ => {
        _this.cargoOwnerLoading = false
      })
    }, 1000),
    // 模糊搜索 账号名 userArr
    remoteQuery2(query) {
      this.userLoading = true
      this.remoteMethod2(query, this)
    },
    remoteMethod2: L.debounce((query, _this) => {
      if (!query) {
        _this.userLoading = false
        return
      }
      httpGetResponse('/ms-warehouse-order/user/findStorageUserList', {
        name: query,
        queryStatus: 2
      }).then(response => {
        const success = dotData(response, 'success')
        if (success) {
          let data = dotData(response, 'data')
          let tempArr = []
          if (Array.isArray(data)) {
            _this.userIdMap.clear() // 清空Map
            data.forEach((v, k) => {
              tempArr.push({
                text: v.name,
                value: v.id
              })
              _this.userIdMap.set(v.id, {phone: v.phone, position: v.roleName}) // 初始化Map对象 和它里面应有的属性
            })
          }
          _this.userArr = tempArr
        }
      }).finally(_ => {
        _this.userLoading = false
      })
    }, 1000)
  }
}
</script>
